package com.hnucm.cooklife.presenter.home;

import com.hnucm.cooklife.base.BasePresenter;
import com.hnucm.cooklife.bean.db.ClasSec;
import com.hnucm.cooklife.contract.clas.Contract;
import com.hnucm.cooklife.model.ClasModel;

import java.util.List;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class ClasPresenter extends BasePresenter<Contract.IClasView> implements Contract.IClasPresenter {

    Contract.IClasModel mIClasModel;

    public ClasPresenter() {
        mIClasModel = new ClasModel();
    }

    @Override
    public void loadClas() {
        if(isViewAttached()){
            getView().onLoading();
        }
        mIClasModel.loadClas()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<List<ClasSec>>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        mCompositeDisposable.add(d);
                    }

                    @Override
                    public void onNext(@NonNull List<ClasSec> clasSecs) {
                        if(isViewAttached()){
                            getView().onLoadClas(clasSecs);
                            getView().onLoadSuccess();
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        e.printStackTrace();
                        if (isViewAttached()) {
                            getView().onLoadingFailed();
                            System.out.println(e.getMessage());
                        }
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    public void refreshClas() {
//todo
    }
}
